package com.unbox.common.configuration.sentinel;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.unbox.common.enums.CodeState;
import com.unbox.common.response.UnboxResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * Sentinel 限流自定义错误
 * @author 王振宇
 */
public class SentinelExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException ex) throws Exception {
        String msg = null;
        UnboxResponse<String> unboxResponse = new UnboxResponse<>();
        if (ex instanceof FlowException) {
            //msg = "限流";
            unboxResponse.setMsg("服务器忙碌,稍后请重试。");
            unboxResponse.setCode(CodeState.SERVICE_BE_BUSY.getValue());
        } else if (ex instanceof DegradeException) {
           // msg = "降级";
            unboxResponse.setMsg("服务器忙碌,稍后请重试。");
        } else if (ex instanceof ParamFlowException) {
           // msg = "热点参数限流";
            unboxResponse.setMsg("服务器忙碌,稍后请重试。");
            unboxResponse.setCode(CodeState.SERVICE_BE_BUSY.getValue());
        } else if (ex instanceof SystemBlockException) {
            //msg = "系统规则（负载/...不满足要求）";
            unboxResponse.setMsg("服务器忙碌,稍后请重试。");
            unboxResponse.setCode(CodeState.SERVICE_BE_BUSY.getValue());
        } else if (ex instanceof AuthorityException) {
           // msg = "授权规则不通过";
            unboxResponse.setMsg("服务器忙碌,稍后请重试。");
            unboxResponse.setCode(CodeState.SERVICE_BE_BUSY.getValue());
        }
        String jsonStr = JSON.toJSONString(unboxResponse);
        // http状态码
        httpServletResponse.setStatus(200);
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        OutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(jsonStr.getBytes());
        outputStream.flush();
        outputStream.close();
    }
}